//
//  HomeUI.m
//  mbstore
//
//  Created by huangyi on 14-3-12.
//  Copyright (c) 2014年 huangyi. All rights reserved.
//

#import "HomeUI.h"

#import "HomeUI.h"
#import "ItemUI.h"
#import "InfoUIM.h"
#import "TreeUIM.h"
#import "ScanUI.h"
#import "CardUIM.h"
#import "ShoppingUIM.h"
#import "ShoppingPromotion.h"
#import "StockUIV.h"
#import "TreeNextUI.h"
#import "MorePopUI.h"
#import "UIImageView+WebCache.h"
//#import "UIImageView+AFNetworking.h"

@interface HomeUI (){
    TreeNextUI *treeNext;
}

@property(nonatomic,weak)UILabel *shoppingText;

@end

@implementation HomeUI

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (1) {
        //           首页
        UIButton *home=[UIButton buttonWithImage:@"home.png"];
        
        
        [home addTarget:self action:@selector(onHomeClick:) forControlEvents:UIControlEventTouchUpInside];
        //           分类
        UIButton *tree=[UIButton buttonWithImage:@"tree.png"];
        
        
        [tree addTarget:self action:@selector(onTreeClick:) forControlEvents:UIControlEventTouchUpInside];
        /*//           SQU
         UIButton *card=[UIButton buttonWithImage:[UIImage imageNamed:@"media.bundle/card.png"]];
         card.frame=CGRectMake(0, 0, 40, 40);
         [card addTarget:self action:@selector(onCardClick:) forControlEvents:UIControlEventTouchUpInside];*/
        NSArray *leftItem=@[home.barButtonItem,tree.barButtonItem];
        self.navigationController.navigationItem.leftBarButtonItems=leftItem;
        //扫描
        UIButton *scan=[UIButton buttonWithImage:@"scan.png"];
        
        
        [scan addTarget:self action:@selector(onScanClick:) forControlEvents:UIControlEventTouchUpInside];
        //           购物袋
        UIButton *shopping=[UIButton buttonWithImage:@"shopping.png"];
        
        [shopping addTarget:self action:@selector(onShoppingClick:) forControlEvents:UIControlEventTouchUpInside];
        
        /*//           促销
         UIButton *activity=[UIButton buttonWithImage:[UIImage imageNamed:@"scanS.png"]];
         activity.frame=CGRectMake(0, 0, 40, 40);
         [activity addTarget:self action:@selector(onActivity:) forControlEvents:UIControlEventTouchUpInside];
         
         //        库存
         UIButton *stock=[UIButton buttonWithImage:[UIImage imageNamed:@"shoppingS.png"]];
         stock.frame=CGRectMake(0, 0, 40, 40);
         [stock addTarget:self action:@selector(onStock:) forControlEvents:UIControlEventTouchUpInside];*/
        UIButton *moreSel=[UIButton buttonWithImage:@"more"];
        
        
        [moreSel addTarget:self action:@selector(onMoreSelect:) forControlEvents:UIControlEventTouchUpInside];
        
        NSArray *rightItem=@[moreSel.barButtonItem,scan.barButtonItem,shopping.barButtonItem];
        self.navigationController.navigationItem.rightBarButtonItems=rightItem;
        
        UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(20, 0, 20, 20)];
        [shopping addSubview:label];
        label.layer.cornerRadius=10;
        label.clipsToBounds=YES;
        label.font=[UIFont systemFontOfSize:12];
        label.textAlignment=NSTextAlignmentCenter;
        label.backgroundColor=[UIColor redColor];
        label.textColor=[UIColor whiteColor];
        self.shoppingText=label;
    }
    self.title =@"Metersbonwe";
    self.navigationItem.leftBarButtonItems=self.navigationController.navigationItem.leftBarButtonItems;
    self.navigationItem.rightBarButtonItems=self.navigationController.navigationItem.rightBarButtonItems;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onReceiveItemListNotification:) name:ItemListNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onReceiveShoppingListNotification:) name:ShoppingListNotification object:nil];
    
    MainApp *app=[MainApp mainApp];
    [app.itemList removeAllObjects];
    
#warning 调用数据库
    //    [app.itemList addObjectsFromArray:[AppUI getAllSuit]];
    ////    NSLog(@"所以的%@",[AppUI getAllSuit]);
    //    [[NSNotificationCenter defaultCenter] postNotificationName:ItemListNotification object:self];
    [[NSNotificationCenter defaultCenter] postNotificationName:ShoppingListNotification object:self];
    
    //    dispatch_async(dispatch_get_main_queue(), ^{
    //        [app requestPromotion];
    //    });
    [self ReloadSearchData];
    responseCtr=[[MBStoreSrv alloc]init];
    [self GetData];
}
-(void)GetData{
    isFinishLoad=YES;
    [responseCtr SearchTagType:tagType
                   CurrentPage:startPage
                      PageSize:endPage
                         CatID:catID
                     SearchKey:strSearchKey
                       Success:^(NSDictionary *arrReceiveData) {
                           MainApp *app=[MainApp mainApp];
                           [app.itemList addObjectsFromArray:[arrReceiveData objectForKey:@"rData"]];
                           total_count=[[[arrReceiveData objectForKey:@"pages"] objectForKey:@"total_count"] intValue];
                           [self reloadItems];
                           //         [[NSNotificationCenter defaultCenter] postNotificationName:ItemListNotification object:self];
                           isFinishLoad=NO;
                       } Failure:^(NSError *error) {
                           isFinishLoad=NO;
                       }];
}
//重新初始化搜索参数
-(void)ReloadSearchData{
    startPage=1;
    endPage=21;
    catID=0;
    tagType=2;
    strSearchKey=@"";
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)onReceiveItemListNotification:(NSNotification *)sender{
    
    [self ShowNextSearch:sender.userInfo];
    self.scrollView.contentOffset=CGPointZero;
    startPage=1;
    tagType=1;
    catID=[[sender.userInfo objectForKey:@"catid"] intValue];
    strSearchKey=[sender.userInfo objectForKey:@"searchKey"];
    [self GetData];
    
}
//    显示下级搜索菜单
-(void)ShowNextSearch:(NSDictionary *)dicNotion{
    if (dicNotion) {
        if ([[dicNotion objectForKey:@"type"] isEqual:@"mainClass"]) {
            if (treeNext ==nil) {
                treeNext=[[TreeNextUI alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
                [self.view addSubview:treeNext];
            }
            treeNext.hidden=NO;
            self.scrollView.frame=CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height-44);
        }
        else{
            treeNext.hidden=YES;
            self.scrollView.frame=CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        }
    }
    
}
-(void)onReceiveShoppingListNotification:(id)sender{
    MainApp *app=[MainApp mainApp];
    int count=[app.shoppingList count];
    self.shoppingText.text=[NSString stringWithFormat:@"%i",count];
}

-(void)openScan{
    ScanUI *scan=[[ScanUI alloc] init];
    [self.navigationController pushViewController:scan animated:YES];
}

-(void)onHomeClick:(id)sender{
    self.scrollView.contentOffset=CGPointZero;
    [self.navigationController popToRootViewControllerAnimated:YES];
    MainApp *app=[MainApp mainApp];
    [app.itemList removeAllObjects];
    [self ReloadSearchData];
    [self GetData];
}
//更多选项
-(void)setSelect:(int)select{
    switch (select) {
        case 0:
            [self onStock:nil];
            break;
        case 1:
            [self onActivity:nil];
            break;
        case 2:
            [self onCardClick:nil];
            break;
        default:
            break;
    }
}
-(void)onTreeClick:(id)sender{
//    下级分类
    if (treeNext) {
        [treeNext HideVieDown];
    }
    [self AddChildWithNavigationController:nil];
     [[NSNotificationCenter defaultCenter] postNotificationName:ChangSelcetType object:@""];
    //    [self presentWithNavigationController:tree];
}

-(void)onScanClick:(UIButton *)sender{
    [self openScan];
}
-(void)onMoreSelect:(UIButton *)sender{
    MorePopUI *moreVie=[[MorePopUI alloc]init];
    moreVie.delegate=self;
    [moreVie showFromView:sender];
    [moreVie setItems:nil];
}
-(void)onCardClick:(id)sender{
    CardUIM *card=[[CardUIM alloc] init];
    [self presentWithNavigationController:card];
}

-(void)onShoppingClick:(id)sender{
    ShoppingUIM *shopping=[[ShoppingUIM alloc] init];
    [self presentWithNavigationController:shopping];
}
-(void)onActivity:(id)sender{
    ShoppingPromotion *promo=[[ShoppingPromotion alloc] init];
    [self presentWithNavigationController:promo];
}
-(void)onStock:(id)sender{
    UIViewController *contrl=[self.navigationController.childViewControllers lastObject];
    if (![contrl isKindOfClass:[StockUIV class]]) {
        StockUIV *stock=[[StockUIV alloc]init];
        [self.navigationController pushViewController:stock animated:YES];
    }
}
-(void)onItemClick:(id)sender{
    if (treeNext) {
        [treeNext HideVieDown];
    }
    UITapGestureRecognizer *tap=sender;
    UIView *itemView=tap.view;
    int idx=itemView.tag;
    ItemUI *item=[[ItemUI alloc] init];
    item.tagType=tagType;
    item.suitIdx=idx;
    [self.navigationController pushViewController:item animated:YES];
    
}

-(void)reloadItems{
    if (self.navigationController.topViewController!=self) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    [self.scrollView removeAllSubviews];
    
    int xoffset=30;//48
    int yoffset=40;//0
    int width=200;//320
    int height=360;
    int space=54;//32
    CGRect cell=CGRectMake(0, 0, width, height);
    int mwidth=0;
    int mheight=0;
    MainApp *app=[MainApp mainApp];
    for (int i=0; i<app.itemList.count; i++) {
        int col=i%3;//2
        int row=floor(i/3);//2
        CGRect r=CGRectOffset(cell, xoffset+(space+width)*col, yoffset+(space+height)*row);
        mwidth=MAX(mwidth, CGRectGetMaxX(r));
        mheight=MAX(mheight, CGRectGetMaxY(r));
        
        UIImageView *imageView=[[UIImageView alloc] initWithFrame:r];
        //        imageView.backgroundColor=[UIColor lightGrayColor];
        imageView.tag=i;
        imageView.clipsToBounds=YES;
        imageView.userInteractionEnabled=YES;
        imageView.contentMode=UIViewContentModeScaleAspectFit;
        [self.scrollView addSubview:imageView];
        
        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onItemClick:)];
        [imageView addGestureRecognizer:tap];
    }
    self.scrollView.contentSize=CGSizeMake(mwidth, mheight);
    [self.scrollView flashScrollIndicators];
    [self scrollViewDidScroll:self.scrollView];
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    scrollView.showsHorizontalScrollIndicator=NO;
    scrollView.showsVerticalScrollIndicator=NO;
    CGRect vis=CGRectMake(scrollView.contentOffset.x, scrollView.contentOffset.y, CGRectGetWidth(scrollView.bounds), CGRectGetHeight(scrollView.bounds));
    for (id view in scrollView.subviews) {
        if ([view isKindOfClass:[UIImageView class]]) {
            UIImageView *imageView=view;
            if (CGRectIntersectsRect(vis, imageView.frame)) {
                //                int idx=imageView.tag;
                //                MainApp *app=[MainApp mainApp];
                //                NSString *itemId=[app.itemList objectAtIndex:idx];
                //                 #warning 调用数据库
                //                NSDictionary *item=[AppUI getSuitDict:itemId];
                //                NSString *imageName=[item valueForKey:@"main_photo"];
                //                //imageName = [imageName stringByReplacingOccurrencesOfString:@" " withString:@"-"];
                //                imageName = [imageName stringByDeletingPathExtension];
                //                imageName = [NSString stringWithFormat:@"%@--w_360_h_360.jpg",imageName];
                //                NSString *imageURL=[AppUI getImageURL:imageName];
                //                [imageView setImageURL:imageURL];
                
                
                
                
                int idx=imageView.tag;
                MainApp *app=[MainApp mainApp];
                NSString *item=[app.itemList objectAtIndex:idx];
                NSString *imageName=[item valueForKey:@"mainPhoto"];
                imageName = [imageName stringByDeletingPathExtension];
                imageName = [NSString stringWithFormat:@"%@--w_360_h_360.jpg",imageName];
                NSString *imageURL=[AppUI getImageURL:imageName];
                [imageView setImageURL:imageURL];
                
                //                [imageView setImageURL:imageName];
                //                [imageView setImageWithURL:[NSURL URLWithString:imageName]];
                //                [imageView setImageURL:[NSURL URLWithString:imageName]];
                
            }else{
                imageView.image=nil;
            }
        }
    }
    scrollView.showsHorizontalScrollIndicator=YES;
    scrollView.showsVerticalScrollIndicator=YES;
}
//下拉刷新
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    MainApp *app=[MainApp mainApp];
    PrevCGPoint=scrollView.contentOffset;
    if (PrevCGPoint.y>scrollView.contentSize.height-scrollView.frame.size.height)
    {
        if (isFinishLoad||total_count==app.itemList.count) return;
        startPage++;
        [self GetData];
    }
    
}

@end
